# -*- coding:utf-8 -*-
import sys, os, re
import codecs

def to_code(pd_name):
    pd_name = pd_name.decode('utf-8')
    nname = ""
    for c in pd_name:
        c = "%04X" % ord(c);
        nname += c
    return nname

def to_char(code):
    return unichr(int(code, 16))

def read_box_chars(folder_name):
    box_file_path = os.path.join(folder_name, "training.box")
    box_file = open(box_file_path)
    count = 1
    line_chars  = ""
    lines = box_file.readlines()
    for line in lines:
        try:
            line_chars = line_chars + to_char(line.split()[0])
            if count % 30 == 0 or count == len(lines):
                print line_chars;
                line_chars = ""
            count = count+1
        except:
            print 'error: %s' % line.split()[0]
            pass

def generate_box_by_draft(training_folder_name):   
    try:
        draft_box_file_path = os.path.join(training_folder_name, 'training_draft.box')
        box_chars_path = os.path.join(training_folder_name, 'training_chars.txt')
        box_file_path = os.path.join(training_folder_name, 'training.box')
    
        draft_box_file = open(draft_box_file_path, 'r', );
        draft_lines = draft_box_file.readlines()
    
        box_chars_file = codecs.open(box_chars_path, 'r', encoding='utf-8')
    
        box_file = open(box_file_path, 'w')
        all_chars = box_chars_file.read()
        chars = all_chars.replace('\r\n', '')
        for i in range(len(chars)):
            box_file.write(to_code(chars[i]) + ' ' + ' '.join(draft_lines[i].split()[1:]) + '\n')
    finally:
        box_file.close()
        box_chars_file.close()
        draft_box_file.close()
if __name__ == '__main__':
    generate_box_by_draft("training_5")
    read_box_chars("training_5")